package serializer

import (
	"app/conf"
	"app/pkg/e"
	"app/pkg/util"
	"encoding/json"
	"fmt"

	"github.com/go-playground/validator/v10"
)

// Response 基础序列化器
type Response struct {
	Code int         `json:"code"`
	Data interface{} `json:"data"`
	Msg  string      `json:"msg"`
}

// DataList 带有总数的Data结构
type DataList struct {
	Item  interface{} `json:"item"`
	Total uint        `json:"total"`
}

// BulidListResponse 带有总数的列表构建器
func BuildListResponse(items interface{}, total uint) Response {
	return Response{
		Code: e.SUCCESS,
		Data: DataList{
			Item:  items,
			Total: total,
		},
		Msg: e.GetMsg(e.SUCCESS),
	}
}

// 根据err返回错误信息
func ErrorResponse(err error) Response {
	code := e.ErrorInvalidParams
	if ve, ok := err.(validator.ValidationErrors); ok {
		code = e.ErrorParamsCheck
		for _, item := range ve {
			field := conf.T(fmt.Sprintf("Field.%s", item.Field()))
			tag := conf.T(fmt.Sprintf("Tag.%s", item.Tag()))
			util.Logger.Info(fmt.Sprintf("%s%s", field, tag))
		}
	}
	if _, ok := err.(*json.UnmarshalTypeError); ok {
		code = e.ErrorInvalidJson
	}
	return Response{
		Code: code,
		Msg:  e.GetMsg(code),
	}
}

// 根据code返回错误信息
func MsgResponse(code int) Response {
	return Response{
		Code: code,
		Msg:  e.GetMsg(code),
	}
}
